﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Forms;
using System.Data;

namespace ThunderStorm
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.tabControl1.SelectionChanged += new SelectionChangedEventHandler(this.tabControl1_SelectedIndexChanged);
            create_Bookmarks();
        }

        private void gobtn_Click(object sender, RoutedEventArgs e)
        {
            //get the selected tab item
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;

            List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

            foreach (Visual vElem in lst)
            {
                //Check whether this is a dockpanel.
                if (vElem.GetType() == typeof(DockPanel))
                {
                    //get the dock panel
                    DockPanel dp = (DockPanel)vElem;

                    if (dp.Children.Count > 0)
                    {
                        System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                        System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                        String url = getURL();
                        urlbox.Text = url;
                        //wkb.Navigate(urlbox.Text);
                        wb.Navigate(url);
                    }
                    else
                    {
                        // Create the interop host control.
                        System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
                        //create a web browser component
                        //WebKitBrowser wkb = new WebKitBrowser();
                        System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
                        wb.ScriptErrorsSuppressed = true;
                        wb.DocumentTitleChanged += new EventHandler(webBrowser_DocumentTitleChanged);
                        // Assign the webkitbrowser control as the host control's child.
                        //host.Child = wkb;
                        host.Child = wb;
                        // Add the interop host control to the Grid
                        // control's collection of child controls.
                        dp.Children.Add(host);
                        //navigate the web browser to the required page
                        String url = getURL();
                        urlbox.Text = url;
                        //wkb.Navigate(urlbox.Text);
                        wb.Navigate(url);
                    }
                }
            }

        }

        private void urlbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //check for modifiers
                if ((Keyboard.Modifiers & (ModifierKeys.Control)) == (ModifierKeys.Control))
                {
                    appendURLSuffix(".com");
                }
                //get the selected tab item
                TabItem tabItem = (TabItem)tabControl1.SelectedItem;

                List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

                foreach (Visual vElem in lst)
                {
                    //Check whether this is a dock panel.
                    if (vElem.GetType() == typeof(DockPanel))
                    {
                        //get the dock panel
                        DockPanel dp = (DockPanel)vElem;

                        if (dp.Children.Count > 0)
                        {
                            System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                            System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                            String url = getURL();
                            urlbox.Text = url;
                            //wkb.Navigate(urlbox.Text);
                            Image LoadingImage = new Image();
                            LoadingImage.Height = 16;
                            LoadingImage.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                            LoadingImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            LoadingImage.Name = "tabCloseImage";
                            LoadingImage.Stretch = Stretch.Fill;
                            LoadingImage.Width = 16;
                            LoadingImage.Margin = new Thickness(0);
                            LoadingImage.Style = (Style)(this.Resources["ajax-loader"]);
                            tabItem.Header = LoadingImage;
                            wb.Navigate(url);
                        }
                        else
                        {
                            // Create the interop host control.
                            System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
                            //create a web browser component
                            //WebKitBrowser wkb = new WebKitBrowser();
                            System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
                            wb.ScriptErrorsSuppressed = true;
                            wb.DocumentTitleChanged += new EventHandler(webBrowser_DocumentTitleChanged);
                            // Assign the webkitbrowser control as the host control's child.
                            //host.Child = wkb;
                            host.Child = wb;
                            // Add the interop host control to the Grid
                            // control's collection of child controls.
                            dp.Children.Add(host);
                            //navigate the web browser to the required page
                            String url = getURL();
                            urlbox.Text = url;
                            //wkb.Navigate(urlbox.Text);
                            Image LoadingImage = new Image();
                            LoadingImage.Height = 16;
                            LoadingImage.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                            LoadingImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            LoadingImage.Name = "tabCloseImage";
                            LoadingImage.Stretch = Stretch.Fill;
                            LoadingImage.Width = 16;
                            LoadingImage.Margin = new Thickness(0);
                            LoadingImage.Style = (Style)(this.Resources["ajax-loader"]);
                            tabItem.Header = LoadingImage;
                            wb.Navigate(url);
                        }
                    }
                }
            }
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;
            urlbox.Text = e.Url.ToString();

            ((System.Windows.Forms.WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
        }

        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            // Ignore the error and suppress the error dialog box. 
            e.Handled = true;
        }

        private void webBrowser_DocumentTitleChanged(object sender, EventArgs e)
        {
            //get the selected tab item
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;

            List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

            foreach (Visual vElem in lst)
            {
                //Check whether this is a web browser.
                if (vElem.GetType() == typeof(DockPanel))
                {
                    //get the dock panel
                    DockPanel dp = (DockPanel)vElem;

                    System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                    System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                    String title = "";

                    if (wb.DocumentTitle.Length > 15)
                    {
                        title = wb.DocumentTitle.Substring(0, 15);
                    }
                    else
                    {
                        title = wb.DocumentTitle;
                    }

                    //create a dockpanel for the header of the tab item
                    DockPanel dpanel = new DockPanel();
                    dpanel.Height = 25;
                    dpanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    dpanel.Name = "tabHeaderPanel";
                    dpanel.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    dpanel.Width = 150;

                    //create a header label for the tab item
                    System.Windows.Controls.Label nl = new System.Windows.Controls.Label();
                    nl.Content = title;
                    nl.Height = 25;
                    nl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    nl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    nl.Name = "tabLabel";
                    nl.FontSize = 12;
                    nl.VerticalContentAlignment = System.Windows.VerticalAlignment.Top;

                    //add it to dock panel
                    dpanel.Children.Add(nl);

                    //create the tab close button for the tab item
                    System.Windows.Controls.Button btn = new System.Windows.Controls.Button();
                    btn.Name = "tabCloseButton_" + tabControl1.SelectedIndex;
                    btn.Width = 20;
                    btn.Height = 20;
                    btn.Padding = new Thickness(0);
                    btn.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

                    Image closeImage = new Image();
                    closeImage.Height = 16;
                    closeImage.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    closeImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    closeImage.Name = "tabCloseImage";
                    closeImage.Stretch = Stretch.Fill;
                    closeImage.Width = 17;
                    closeImage.Style = (Style)(this.Resources["CloseImageStyle"]);

                    btn.Content = closeImage;
                    btn.Click += new RoutedEventHandler(CloseButtonClick);
                    //add the close button to dock panel
                    dpanel.Children.Add(btn);

                    //add the dock panel to the tab item header
                    tabItem.Header = dpanel;
                }
            }
        }

        private string appendURLSuffix(string suffix)
        {
            String url = urlbox.Text;
            url = url + suffix;
            urlbox.Text = url;
            return url;
        }

        private string getURL()
        {
            String url = urlbox.Text;
            string[] extarr = new string[]
	        {
	            ".com",
	            ".org",
                ".net",
	            ".gov",
	            ".in",
                ".uk"
	        };

            Boolean extflg = false;
            //check if http is present
            foreach (string x in extarr)
            {
                if (url.Contains(x))
                {
                    extflg = true;
                }
            }

            if (extflg == true)
            {
                bool test1 = url.StartsWith("http", System.StringComparison.CurrentCultureIgnoreCase);

                if (test1 == false)
                {
                    bool test2 = url.StartsWith("www", System.StringComparison.CurrentCultureIgnoreCase);

                    if (test2 == false)
                    {
                        url = "http://www." + url;
                    }
                    else
                    {
                        url = "http://" + url;
                    }
                }
            }
            else
            {
                url = "http://www.google.com/search?q=" + url.Replace(" ", "+");
            }
            return url;
        }

        private void tabControl1_SelectedIndexChanged(Object sender, EventArgs e)
        {
            int selectedindex = tabControl1.SelectedIndex;
            Boolean addtabflg = false;
            if (selectedindex > -1)
            {
                TabItem tabItem = (TabItem)tabControl1.Items.GetItemAt(selectedindex);

                if (tabItem.Name.Equals("addTab"))
                {
                    if (addtabflg == false)
                    {
                        addtabflg = true;
                        ////remove the addTabs tab page
                        tabControl1.Items.Remove(tabItem);

                        //create a new tab item
                        TabItem myTabItem = new TabItem();
                        myTabItem.Style = (Style)(this.Resources["TabStyle"]);
                        myTabItem.Name = "TabItem_" + tabControl1.Items.Count;

                        //create a dockpanel for the header of the tab item
                        DockPanel dp = new DockPanel();
                        dp.Height = 25;
                        dp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        dp.Name = "tabHeaderPanel";
                        dp.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                        dp.Width = 150;

                        //create a header label for the tab item
                        System.Windows.Controls.Label nl = new System.Windows.Controls.Label();
                        nl.Content = "New Tab";
                        nl.Height = 25;
                        nl.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        nl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        nl.Name = "tabLabel";
                        nl.FontSize = 14;

                        //add it to dock panel
                        dp.Children.Add(nl);

                        //create the tab close button for the tab item
                        System.Windows.Controls.Button btn = new System.Windows.Controls.Button();
                        btn.Name = "tabCloseButton_" + tabControl1.Items.Count;
                        btn.Width = 20;
                        btn.Height = 20;
                        btn.Margin = new Thickness(0);
                        btn.Padding = new Thickness(0);
                        btn.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

                        Image closeImage = new Image();
                        closeImage.Height = 16;
                        closeImage.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        closeImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                        closeImage.Name = "tabCloseImage";
                        closeImage.Stretch = Stretch.Fill;
                        closeImage.Width = 16;
                        closeImage.Margin = new Thickness(0);
                        closeImage.Style = (Style)(this.Resources["CloseImageStyle"]);

                        btn.Content = closeImage;
                        btn.Click += new RoutedEventHandler(CloseButtonClick);
                        //add the close button to dock panel
                        dp.Children.Add(btn);

                        //add the dock panel to the tab item header
                        myTabItem.Header = dp;

                        //create a grid for the body
                        System.Windows.Controls.Grid gd = new Grid();

                        //create a dock panel for the grid
                        DockPanel dpb = new DockPanel();
                        dpb.SetValue(ColumnDefinition.WidthProperty, GridLength.Auto);
                        dpb.SetValue(RowDefinition.HeightProperty, GridLength.Auto);
                        dpb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                        dpb.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

                        //add the dock panel to the grid
                        gd.Children.Add(dpb);

                        //add the grid to the tab item
                        myTabItem.Content = gd;

                        //add the tab item to the tab control
                        tabControl1.Items.Add(myTabItem);

                        //add the addtabs tab page
                        tabControl1.Items.Add(addTab);

                        //now set the selected tab
                        tabControl1.SelectedItem = myTabItem;
                        tabControl1.Focus();

                        //set focus to the urlbar
                        //urlbox.SelectAll();
                        //urlbox.Focus();
                    }
                }
                else if (tabItem != null)
                {
                    //now set the selected tab
                    tabControl1.SelectedItem = tabItem;

                    List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

                    foreach (Visual vElem in lst)
                    {
                        //Check whether this is a dockpanel.
                        if (vElem.GetType() == typeof(DockPanel))
                        {
                            //get the dock panel
                            DockPanel dp = (DockPanel)vElem;

                            if (dp.Children.Count > 0)
                            {
                                System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                                System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                                urlbox.Text = wb.Url.ToString();
                                urlbox.SelectAll();
                            }
                            else
                            {
                                urlbox.Text = "";
                                urlbox.SelectAll();
                            }
                        }
                    }

                    //set focus to the urlbar
                    urlbox.Focus();
                }
            }
        }

        private void CloseButtonClick(object sender, EventArgs e)
        {
            System.Windows.Controls.Button clicked = (System.Windows.Controls.Button)sender;
            string[] arrnames = clicked.Name.Split('_');
            int index = int.Parse(arrnames[1]);
            //System.Windows.MessageBox.Show(clicked.Name + "-" + tabControl1.Items.Count);
            if (arrnames[0].Equals("tabCloseButton"))
            {
                foreach (TabItem item in tabControl1.Items)
                {
                    if (item.Name.Equals("TabItem_" + index))
                    {
                        if (tabControl1.Items.Count > 1)
                        {
                            tabControl1.SelectedIndex = index - 1;
                            tabControl1.Items.Remove(item);
                            return;
                        }
                    }
                }
            }
        }

        private void prevbtn_Click(object sender, RoutedEventArgs e)
        {
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;

            List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

            foreach (Visual vElem in lst)
            {
                //Check whether this is a dockpanel.
                if (vElem.GetType() == typeof(DockPanel))
                {
                    //get the dock panel
                    DockPanel dp = (DockPanel)vElem;

                    if (dp.Children.Count > 0)
                    {
                        System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                        System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                        if (wb.CanGoBack)
                        {
                            Boolean result = wb.GoBack();
                            urlbox.Text = wb.Url.ToString();

                            if (result == true)
                            {
                                //urlbox.Text = wb.Url.ToString();
                            }
                            wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
                        }
                        urlbox.SelectAll();
                    }
                    else
                    {
                        urlbox.SelectAll();
                    }
                }
            }

            //set focus to the urlbar
            urlbox.Focus();
        }

        private void nextbtn_Click(object sender, RoutedEventArgs e)
        {
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;

            List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

            foreach (Visual vElem in lst)
            {
                //Check whether this is a dockpanel.
                if (vElem.GetType() == typeof(DockPanel))
                {
                    //get the dock panel
                    DockPanel dp = (DockPanel)vElem;

                    if (dp.Children.Count > 0)
                    {
                        System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                        System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                        if (wb.CanGoForward)
                        {
                            Boolean result = wb.GoForward();
                            if (result == true)
                            {
                                //urlbox.Text = wb.Url.ToString();
                            }
                        }
                        urlbox.SelectAll();
                        wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
                    }
                    else
                    {
                        urlbox.SelectAll();
                    }
                }
            }

            //set focus to the urlbar
            urlbox.Focus();
        }

        private void refreshbtn_Click(object sender, RoutedEventArgs e)
        {
            TabItem tabItem = (TabItem)tabControl1.SelectedItem;

            List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)tabItem.Content);

            foreach (Visual vElem in lst)
            {
                //Check whether this is a dockpanel.
                if (vElem.GetType() == typeof(DockPanel))
                {
                    //get the dock panel
                    DockPanel dp = (DockPanel)vElem;

                    if (dp.Children.Count > 0)
                    {
                        System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dp.Children[0];
                        System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                        wb.Refresh();
                        urlbox.SelectAll();
                        //wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
                    }
                    else
                    {
                        urlbox.SelectAll();
                    }
                }
            }

            //set focus to the urlbar
            urlbox.Focus();
        }

        private void createBookmark(String Name, String Url)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<String, String>();
            data.Add("Name", Name);
            data.Add("Url", Url);
            try
            {
                if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Url))
                    db.Insert("bookmarks", data);
            }
            catch (Exception crap)
            {
                System.Windows.MessageBox.Show(crap.Message);
            }
        }

        private void bookmarkbtn_Click(object sender, RoutedEventArgs e)
        {
            String Name = urlbox.Text.Replace("http://", "");
            Name = Name.Replace("https://", "");
            Name = Name.Replace("www.", "");
            Name = Name.Replace(".com", "");
            int firstocc = Name.IndexOf("/");
            if (firstocc > 0)
            {
                Name = Name.Substring(0, firstocc);
            }
            bName.Text = Name;
            bUrl.Text = urlbox.Text;
            this.Popup1.IsOpen = true;
        }

        private void popupsubmit_Click(object sender, RoutedEventArgs e)
        {
            createBookmark(bName.Text, bUrl.Text);

            //Add this to the bookmarks menu
            System.Windows.Controls.MenuItem newMenuItem = new System.Windows.Controls.MenuItem();
            newMenuItem.Header = bName.Text;
            newMenuItem.Name = bName.Text;
            newMenuItem.Click += new RoutedEventHandler(bookmarks_Click);
            System.Windows.Controls.MenuItem Bookmarks = (System.Windows.Controls.MenuItem)booksmarksmenu.Items.GetItemAt(0);
            Bookmarks.Items.Add(newMenuItem);

            bName.Text = "";
            bUrl.Text = "";
            this.Popup1.IsOpen = false;
        }


        private void create_Bookmarks()
        {
            System.Windows.Controls.MenuItem Bookmarks = (System.Windows.Controls.MenuItem)booksmarksmenu.Items.GetItemAt(0);
            try
            {
                SQLiteDatabase db = new SQLiteDatabase();
                DataTable bkmarks;
                String query = "select Name \"Name\", Url \"Url\"";
                query += "from bookmarks;";
                bkmarks = db.GetDataTable(query);

                foreach (DataRow r in bkmarks.Rows)
                {
                    System.Windows.Controls.MenuItem newMenuItem = new System.Windows.Controls.MenuItem();
                    newMenuItem.Header = (r["Name"].ToString());
                    newMenuItem.Name = (r["Name"].ToString().Trim());
                    newMenuItem.Click += new RoutedEventHandler(bookmarks_Click);
                    Bookmarks.Items.Add(newMenuItem);
                }
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                System.Windows.MessageBox.Show(error);
                this.Close();
            }
        }

        private void bookmarks_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.MenuItem mi = e.Source as System.Windows.Controls.MenuItem;

            try
            {
                SQLiteDatabase db = new SQLiteDatabase();
                DataTable bkmarks;
                String query = "select Name \"Name\", Url \"Url\"";
                query += "from bookmarks;";
                bkmarks = db.GetDataTable(query);

                foreach (DataRow r in bkmarks.Rows)
                {
                    if (r["Name"].ToString().Equals(mi.Name))
                    {
                        int selectedindex = tabControl1.Items.Count;
                        TabItem tabItem = (TabItem)tabControl1.Items.GetItemAt(selectedindex - 1);

                        ////remove the addTabs tab page
                        tabControl1.Items.Remove(tabItem);

                        //create a new tab item
                        TabItem myTabItem = new TabItem();
                        myTabItem.Style = (Style)(this.Resources["TabStyle"]);
                        myTabItem.Name = "TabItem_" + tabControl1.Items.Count;

                        //create a dockpanel for the header of the tab item
                        DockPanel dp = new DockPanel();
                        dp.Height = 25;
                        dp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        dp.Name = "tabHeaderPanel";
                        dp.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                        dp.Width = 150;

                        //create a header label for the tab item
                        System.Windows.Controls.Label nl = new System.Windows.Controls.Label();
                        nl.Content = "New Tab";
                        nl.Height = 25;
                        nl.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        nl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        nl.Name = "tabLabel";
                        nl.FontSize = 14;

                        //add it to dock panel
                        dp.Children.Add(nl);

                        //create the tab close button for the tab item
                        System.Windows.Controls.Button btn = new System.Windows.Controls.Button();
                        btn.Name = "tabCloseButton_" + tabControl1.Items.Count;
                        btn.Width = 20;
                        btn.Height = 20;
                        btn.Margin = new Thickness(0);
                        btn.Padding = new Thickness(0);
                        btn.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

                        Image closeImage = new Image();
                        closeImage.Height = 16;
                        closeImage.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        closeImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                        closeImage.Name = "tabCloseImage";
                        closeImage.Stretch = Stretch.Fill;
                        closeImage.Width = 16;
                        closeImage.Margin = new Thickness(0);
                        closeImage.Style = (Style)(this.Resources["CloseImageStyle"]);

                        btn.Content = closeImage;
                        btn.Click += new RoutedEventHandler(CloseButtonClick);
                        //add the close button to dock panel
                        dp.Children.Add(btn);

                        //add the dock panel to the tab item header
                        myTabItem.Header = dp;

                        //create a grid for the body
                        System.Windows.Controls.Grid gd = new Grid();

                        //create a dock panel for the grid
                        DockPanel dpb = new DockPanel();
                        dpb.SetValue(ColumnDefinition.WidthProperty, GridLength.Auto);
                        dpb.SetValue(RowDefinition.HeightProperty, GridLength.Auto);
                        dpb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                        dpb.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

                        //add the dock panel to the grid
                        gd.Children.Add(dpb);

                        //add the grid to the tab item
                        myTabItem.Content = gd;

                        //add the tab item to the tab control
                        tabControl1.Items.Add(myTabItem);

                        //add the addtabs tab page
                        tabControl1.Items.Add(addTab);

                        //now set the selected tab
                        tabControl1.SelectedItem = myTabItem;
                        tabControl1.Focus();

                        List<Visual> lst = VisualTreeEnumHelper.GetAllControls((Visual)myTabItem.Content);

                        foreach (Visual vElem in lst)
                        {
                            //Check whether this is a dock panel.
                            if (vElem.GetType() == typeof(DockPanel))
                            {
                                //get the dock panel
                                DockPanel dpc = (DockPanel)vElem;

                                if (dpc.Children.Count > 0)
                                {
                                    System.Windows.Forms.Integration.WindowsFormsHost host = (System.Windows.Forms.Integration.WindowsFormsHost)dpc.Children[0];
                                    System.Windows.Forms.WebBrowser wb = (System.Windows.Forms.WebBrowser)host.Child;
                                    String url = getURL();
                                    urlbox.Text = url;
                                    //wkb.Navigate(urlbox.Text);
                                    wb.Navigate(url);
                                }
                                else
                                {
                                    // Create the interop host control.
                                    System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
                                    //create a web browser component
                                    //WebKitBrowser wkb = new WebKitBrowser();
                                    System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
                                    wb.ScriptErrorsSuppressed = true;
                                    wb.DocumentTitleChanged += new EventHandler(webBrowser_DocumentTitleChanged);
                                    // Assign the webkitbrowser control as the host control's child.
                                    //host.Child = wkb;
                                    host.Child = wb;
                                    // Add the interop host control to the Grid
                                    // control's collection of child controls.
                                    dpc.Children.Add(host);
                                    //navigate the web browser to the required page
                                    String url = r["Url"].ToString();
                                    urlbox.Text = url;
                                    //wkb.Navigate(urlbox.Text);
                                    wb.Navigate(url);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                System.Windows.MessageBox.Show(error);
                this.Close();
            }
        }

        private void popupcancel_Click(object sender, RoutedEventArgs e)
        {
            bName.Text = "";
            bUrl.Text = "";
            this.Popup1.IsOpen = false;
        }

        private void help_Click(object sender, RoutedEventArgs e)
        {

        }

        private void about_Click(object sender, RoutedEventArgs e)
        {

        }
    }

    //Helper class for enumerating the VisualTree
    public class VisualTreeEnumHelper
    {
        private static List<Visual> _lst;

        public static List<Visual> GetAllControls(Visual vElementRoot)
        {
            _lst = new List<Visual>();
            EnumVisualTree(vElementRoot);
            return _lst;
        }

        private static void EnumVisualTree(Visual vElementRoot)
        {
            for (int intCounter = 0; intCounter < VisualTreeHelper.GetChildrenCount(vElementRoot); intCounter++)
            {
                //Get the control
                Visual child = (Visual)VisualTreeHelper.GetChild(vElementRoot, intCounter);
                //Add it to the list
                _lst.Add(child);
                //Process all children
                EnumVisualTree(child);
            }
        }
    }
}
